#include<iostream>
#include<sys/types.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string>
#include"log.hpp"
#include <cstring>
#include <unistd.h>
#include "Thread.hpp"
#include<memory>

uint16_t serverport;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " serverIp serverPort\n" << std::endl;
}


static void* udpSend(void* args)
{
    int sock = *((int*)((ThreadData*)args)->args_);
    // std::string name = ((ThreadData*)args)->name_;
    
    std::string message;
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(true)
    {
        std::cerr<<"请输入你的信息# "; 
        std::getline(std::cin,message);
        if(message == "quit")
        {
            break;
        }
        sendto(sock,message.c_str(),message.size(),0,(sockaddr*)&server,sizeof server);
    }
    return nullptr;
}

static void* udpRecv(void* args)
{
    int sock = *((int*)((ThreadData*)args)->args_);

    char buffer[256];
    while(true)
    {
        bzero(buffer,sizeof buffer);
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;

        ssize_t s = recvfrom(sock,buffer,sizeof(buffer)-1,0,(sockaddr*)&temp,&len);

        if(s>0)
        {
            buffer[s] = 0;
            std::cout<<buffer<<std::endl;
        }
    }

    return nullptr;
}

int main(int argc,char* argv[])
{
    if(argc !=3)
    {
        usage(argv[0]);
        exit(1);
    }

    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock<0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    serverport = atoi(argv[2]);
    serverip = argv[1];



    std::string message;
    struct sockaddr_in server;
    bzero(&server,sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(atoi(argv[2]));

    std::unique_ptr<Thread> sender(new Thread(1,udpSend,(void*)&sock));
    std::unique_ptr<Thread> recver(new Thread(1,udpRecv,(void*)&sock));

    sender->start();
    recver->start();

    sender->join();
    recver->join();

    // char buffer[256];
    // while(true)
    // {
    //     std::cout << "请输入你的信息# ";
    //     std::getline(std::cin,message);
    //     if(message=="quit")
    //         break;
        
    //     sendto(sock,message.c_str(),message.size(),0,(sockaddr*)&server,sizeof(server));

    //     struct sockaddr_in temp;
    //     bzero(&temp,sizeof temp);
    //     socklen_t len = sizeof temp;

    //     ssize_t s = recvfrom(sock,buffer,sizeof buffer,0,(sockaddr*)&temp,&len);
    //     if(s>0)
    //     {
    //         buffer[s] = 0;
    //         std::cout << "server echo# " << buffer << std::endl;
    //     }
    // }
    close(sock);
    return 0;
}